import * as Handlebars from "handlebars";
import { Moment } from "moment";
import { Unit } from "./entity-types";
import { toDateInfo } from "./unit-cal";
import { htmlIcon, htmlSymbol } from "./utils";
import { formatDate, formatDateTime, formatTime, formatToLunar } from "./utils-date";

Handlebars.registerHelper("echo", function (cond: string, val: any) {
	return (cond) ? val : "";
});

Handlebars.registerHelper("ico", function (name: string, options: any) {
	return htmlIcon(name);
});

Handlebars.registerHelper("symbol", function (name: string, options: any) {
	return htmlSymbol(name);
});

// we can use like this {{{incl "tmpl-test" data ...}}}
Handlebars.registerHelper("incl", function (templateName: string, data: any, options: any) {
	var params = Array.prototype.slice.call(arguments, 1, arguments.length - 1);
	if (params.length == 1) {
		params = params[0];
	}

	var tmpl = Handlebars.templates[templateName];
	var html = tmpl(params);
	return html;
});

Handlebars.registerHelper("display", function (val1: string, val2: string) {
	return (val1) ? val1 : val2;
});

Handlebars.registerHelper("formatDate", function (value: Moment, format: string, options: any) {
	let f;
	if (arguments.length > 2) {
		f = format;
	}
	return formatDate(value, f);
});

Handlebars.registerHelper("formatTime", function (value: Moment, format: string, options: any) {
	let f;
	if (arguments.length > 2) {
		f = format;
	}
	return formatTime(value, f);
});

Handlebars.registerHelper("formatDateTime", function (value: Moment, format: string, options: any) {
	let f;
	if (arguments.length > 2) {
		f = format;
	}
	return formatDateTime(value, f);
});

Handlebars.registerHelper("formatToLunar", function (value: Moment, format: string, options: any) {
	let f;
	if (arguments.length > 2) {
		f = format;
	}
	return formatToLunar(value, f);
});

Handlebars.registerHelper("isPlusDate", function (this: any, value: Moment, unit: Unit, options: any) {
	const dateInfo = toDateInfo(value, unit.isLunar);
	return dateInfo.day == unit.day ? options.inverse(this) : options.fn(this);
});
